package com.guchenbo.hadoop.demo;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;

import javax.security.auth.Subject;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;

public class ProxyUser {

  public static void main(String[] args) throws Exception {
    Configuration configuration = new Configuration();
    configuration.addResource("/Users/guchenbo/opt/etc/hadoop/ark32/core-site.xml");
    configuration.addResource("/Users/guchenbo/opt/etc/hadoop/ark32/hdfs-site.xml");
    configuration.addResource("/Users/guchenbo/opt/etc/hadoop/ark32/hive-site.xml");
    configuration.addResource("/Users/guchenbo/opt/etc/hadoop/ark32/yarn-site.xml");

    Subject subject = new Subject();
    // 真正使用认证信息的用户
    // 设置了环境变量 HADOOP_USER_NAME=admin ，那么 这个 superUgi=admin
    UserGroupInformation superUgi = UserGroupInformation.getCurrentUser();

    FileSystem fileSystem = FileSystem.get(configuration);
    Path path = new Path("/user/guchenbo");

    noProxy(fileSystem, path);
//    proxy(fileSystem, path, superUgi);

  }

  private static void noProxy(FileSystem fileSystem, Path path) throws IOException {
    boolean f = fileSystem.mkdirs(new Path("/user/guchenbo/test"));
    System.out.println(f);
  }

  private static void proxy(FileSystem fileSystem, Path path, UserGroupInformation superUgi)
      throws IOException, InterruptedException {
    // gcb是被代理的用户
    UserGroupInformation proxyUgi = UserGroupInformation.createProxyUser("yarn", superUgi);
    proxyUgi.doAs((PrivilegedExceptionAction<Void>) () -> {
      fileSystem.mkdirs(new Path("test"));
      return null;
    });
  }

}
